Two Sum II - Input Array is Sorted

Find indices of two numbers that add up to target in a sorted input
array
two pointers
Author

Isaac Flath

Published

February 19, 2024

Problem Source: Leetcode

Problem Description

Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 <= numbers.length.

Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

The tests are generated such that there is exactly one solution. You may not use the same element twice.

Your solution must use only constant extra space.

tests

def test(fn):
    numbers = [2,7,11,15]
    target = 9
    expected = (1,2)
    assert fn(numbers,target) == expected 

    numbers = [2,3,4]
    target = 6
    expected = (1,3)
    assert fn(numbers,target) == expected 

    numbers = [-1,0]
    target = -1
    expected = (1,2)
    assert fn(numbers,target) == expected 

Solution

  • Time Complexity: O(1)
  • Space Complexity: O(n)
from typing import List
def twoSum(numbers: List[int], target: int) -> List[int]:
    # start at each end of the list
    i1, i2 = 0, len(numbers) - 1

    while i1 < i2:
        curr_sum = numbers[i1] + numbers[i2]

        if curr_sum < target: # If too small
            i1 += 1 # make it bigger
        elif curr_sum > target: # If too big
            i2 -= 1 # make it smaller
        else:
            return i1+1, i2+1 # if juuussstt right

test(twoSum)